#import "Tools.h"


@implementation Tools
#pragma mark 判断字符串
+ (BOOL)isEmpty:(NSString *)string
{
    if (![string isKindOfClass:[NSString class]])
        string = [string description];
    if (string == nil || string == NULL)
        return YES;
    if ([string isKindOfClass:[NSNull class]])
        return YES;
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0)
        return YES;
    if ([string isEqualToString:@"(null)"])
        return YES;
    if ([string isEqualToString:@"(null)(null)"])
        return YES;
    if ([string isEqualToString:@"<null>"])
        return YES;
    if ([string isEqualToString:@""])
        return YES;
    
    // return Default
    return NO;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

#pragma mark 抖动
+ (void)shakeView:(UIView*)viewToShake
{
    CGFloat t =4.0;
    CGAffineTransform translateRight  =CGAffineTransformTranslate(CGAffineTransformIdentity, t,0.0);
    CGAffineTransform translateLeft =CGAffineTransformTranslate(CGAffineTransformIdentity,-t,0.0);
    viewToShake.transform = translateLeft;
    [UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat animations:^{
        [UIView setAnimationRepeatCount:2.0];
        viewToShake.transform = translateRight;
    } completion:^(BOOL finished){
        if(finished){
            [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                viewToShake.transform =CGAffineTransformIdentity;
            } completion:NULL];
        }
    }];
}

#pragma mark 手机号码验证
/*
 电话号码
 移动  134［0-8］ 135 136 137 138 139 150 151 152 158 159 182 183 184 157 187 188 147 178
 联通  130 131 132 155 156 145 185 186 176
 电信  133 153 180 181 189 177
 
 上网卡专属号段
 移动 147
 联通 145
 
 虚拟运营商专属号段
 移动 1705
 联通 1709
 电信 170 1700
 
 卫星通信 1349
 */

+ (BOOL) isValidateMobile:(NSString *)mobile
{
    NSString * phoneRegex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}


#pragma mark 是否含有非法字符
+ (BOOL)JudgeTheillegalCharacter:(NSString *)content{
    
    NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    
    NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    
    if (![emailTest evaluateWithObject:content]) {
        
        return YES;
        
    }
    
    return NO;
    
}

#pragma mark 获取UUID
+ (NSString *)getUUID {
    static NSString* uuid_saving_string = @"bocai_uuid_saving_string";
    NSString* uuid = [[NSUserDefaults standardUserDefaults] objectForKey:uuid_saving_string];
    if (uuid == nil) {
        uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
        [[NSUserDefaults standardUserDefaults] setObject:uuid forKey:uuid_saving_string];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
    
    return uuid;
}

+ (NSString *)getVersion {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
}

+ (NSString *)getBuild {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
}

+ (NSString *)getPhoneName {
    return [[UIDevice currentDevice] name];
}

+ (CGPoint)centerOfView:(UIView*)view {
    return CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2);
}


+ (NSString*)formattedCoinString:(NSInteger)coin {
    CGFloat result = coin;
    NSString *unitString = @"";
    NSUInteger unit = 10000;
    if (result >= unit) {
        result = result / unit;
        unitString = @"万";
        
        if (result >= unit) {
            result = result / unit;
            unitString = @"亿";
        }
        
        if (result >= unit) {
            result = result / unit;
            unitString = @"万亿";
        }
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = kCFNumberFormatterNoStyle;
        formatter.roundingMode = NSNumberFormatterRoundDown;
        formatter.maximumFractionDigits = 3;
        return [NSString stringWithFormat:@"%@%@", [formatter stringFromNumber:@(result)], unitString];
    } else {
        return [NSString stringWithFormat:@"%ld", coin];
    }
}

#pragma mark 判断时间是否是在今天

+(BOOL)isCurrentDay:(NSDate *)aDate
{
    if (aDate==nil) return NO;

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:aDate];
    NSDate *otherDate = [cal dateFromComponents:components];
    if([today isEqualToDate:otherDate])
        return YES;
    return NO;
}

#pragma mark 获取视图的控制器
+(id)findResponder:(Class)dst selfs:(id)src{
    UIResponder *next = [src nextResponder];
    while (next) {
        if ([next isKindOfClass:dst]) return next;
        next = next.nextResponder;
    }
    return nil;
}

#pragma mark 获得nib视图
+ (id)loadFirstNibWithName:(NSString *)name
{
    NSArray* objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
    return [objects objectAtIndex:0];
}

#pragma mark json 转字典
+(id)JSONWithData:(NSData *)data{
    NSError *err;
    
    id result = [NSJSONSerialization JSONObjectWithData:data
                                                options:NSJSONReadingMutableContainers
                 
                                                  error:&err];
    return result;
}

#pragma mark  取到等级图片路径

+ (CGFloat)getGameAreaHeight {
    CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
    if (width == 375){ //6
        return 200;
    } else if (width == 414){ //6+
        return 215;
    }
    return 175; //5,5s,5c,5e
}





#pragma mark 获取当前的网络
+ (int)getCurrentNetWork{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"] subviews];
    int netType = 0;
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            
            switch (netType) {
                case 0:
                    netType = 0;
                    break;
                case 1:
                    netType = 2;
                    break;
                case 2:
                    netType = 3;
                    break;
                case 3:
                    netType = 4;
                    break;
                case 5:
                    netType = 1;
                    break;
                default:
                    netType = -1;
                    break;
            }
        }
    }
    return netType;
}

+(BOOL)isHasNetWork{
    
    int type = [Tools getCurrentNetWork];
    
    if (type > 0) {
        return YES;
    }else{
        return NO;
    }
    
}
//将date时间戳转变成时间字符串
//@paaram   date            用于转换的时间
//@param    formatString    时间格式(yyyy-MM-dd HH:mm:ss)
//@return   NSString        返回字字符如（2012－8－8 11:11:11）
+ (NSString *)getDateStringWithDate:(NSString *)dateStr
                         DateFormat:(NSString *)formatString
{
    
    NSInteger num = [dateStr integerValue];//（重点）
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:formatString];
    
    NSDate*confromTimesp = [NSDate dateWithTimeIntervalSince1970:num];
    NSString*confromTimespStr = [formatter stringFromDate:confromTimesp];
//    NSLog(@"%@",confromTimespStr);
    return confromTimespStr;
}


//计算时间差
+(NSString * )getUserAge:(NSString *)birthdayStr{
    
    NSDate *date = [Tools dateFromString:birthdayStr format:@"yyyy-MM-dd"];
    
    int dayNum = [[TimeTool getTimeDiffString:[Tools cTimestampFromDate:date]]intValue];
    NSString * ageStr =[NSString stringWithFormat:@"%d",dayNum/365];
    return ageStr;
}


+(NSString*)getCurrentTimestamp{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%.5f", a];//转为字符型
    return timeString;
}

/**
 *  字符串转时间戳
 *
 *  @param theTime 字符串时间
 *  @param format  转化格式 如yyyy-MM-dd HH:mm:ss,即2015-07-15 15:00:00
 *
 *  @return 返回时间戳的字符串
 */

+(NSString *)cTimestampFromString:(NSString *)timeStr
                          format:(NSString *)format
{
    NSDate *date = [Tools dateFromString:timeStr format:format];
    NSString * str =[NSString stringWithFormat:@"%ld",[Tools cTimestampFromDate:date]];
    return str;
}




+ (NSInteger)cTimestampFromDate:(NSDate *)date
{
    return (long)[date timeIntervalSince1970];
}
//获取时长
+ (NSString *)getTimeStrWithTimeInterval:(NSInteger)duration{
    int second = duration%60;
    int value = (int)duration/60;
    int minute = value%60;
    int hour = value/60;
    NSString *time = [NSString stringWithFormat:@"时长:"];
    time = [time stringByAppendingFormat:@"%d%d小时",hour/10,hour%10];
    time = [time stringByAppendingFormat:@"%d%d分钟",minute/10,minute%10];
    time = [time stringByAppendingFormat:@"%d%d秒",second/10,second%10];
    return time;
}
//*  字符串转NSDate
+ (NSDate *)dateFromString:(NSString *)timeStr
                    format:(NSString *)format
{
    NSDateFormatter *dateFormatter =  [Tools defaultFormatter];
    [dateFormatter setDateFormat:format];
    NSDate *date = [dateFormatter dateFromString:timeStr];
    return date;
}
//*  NSDate转字符串
+ (NSString *)datestrFromDate:(NSDate *)date
               withDateFormat:(NSString *)format{
    NSDateFormatter* dateFormat = [Tools defaultFormatter];
    [dateFormat setDateFormat:format];
    return [dateFormat stringFromDate:date];
}

static NSDateFormatter *dateFormatter;
+(NSDateFormatter *)defaultFormatter
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateFormatter = [[NSDateFormatter alloc]init];
    });
    return dateFormatter;
}


#pragma mark - 时间段问候

//获取时间段
+(NSString *)getTheTimeBucket
{
    //    NSDate * currentDate = [self getNowDateFromatAnDate:[NSDate date]];
    
    NSDate * currentDate = [NSDate date];
    if ([currentDate compare:[self getCustomDateWithHour:0]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:9]] == NSOrderedAscending)
    {
        return @"早上好";
    }
    else if ([currentDate compare:[self getCustomDateWithHour:9]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:11]] == NSOrderedAscending)
    {
        return @"上午好";
    }
    else if ([currentDate compare:[self getCustomDateWithHour:11]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:13]] == NSOrderedAscending)
    {
        return @"中午好";
    }
    else if ([currentDate compare:[self getCustomDateWithHour:13]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:18]] == NSOrderedAscending)
    {
        return @"下午好";
    }
    else
    {
        return @"晚上好";
    }
}

//将时间点转化成日历形式
+ (NSDate *)getCustomDateWithHour:(NSInteger)hour
{
    //获取当前时间
    NSDate * destinationDateNow = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *currentComps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    currentComps = [currentCalendar components:unitFlags fromDate:destinationDateNow];
    
    //设置当前的时间点
    NSDateComponents *resultComps = [[NSDateComponents alloc] init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [resultCalendar dateFromComponents:resultComps];
}

#pragma mark - 生成随机数
+ (float)randomFloatFromMin:(float)min max:(float)max {
    return ((arc4random() % RAND_MAX) / (RAND_MAX * 1.0)) * (max - min) + min;
}

+ (CGSize)expectedSizeLabel:(UILabel*)label {
    [label setNumberOfLines:1];
    CGSize maximumLabelSize = CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(label.bounds));
    CGSize expectedLabelSize = [[label text] sizeWithFont:[label font]
                                       constrainedToSize:maximumLabelSize
                                           lineBreakMode:[label lineBreakMode]];
    return expectedLabelSize;
}

+ (id)random:(NSArray*)array {
    if (array && array.isNotEmpty) {
        NSInteger index = arc4random() % array.count;
        return array[index];
    }
    return nil;
}


#pragma mark 页面跳转

+(UIWindow*)find_top_window
{
    NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
    for (UIWindow *window in frontToBackWindows){
        BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
        BOOL windowIsVisible = !window.hidden && window.alpha > 0;
        BOOL windowLevelNormal = window.windowLevel == UIWindowLevelNormal;
        
        if (windowOnMainScreen && windowIsVisible && windowLevelNormal) {
            return window;
        }
    }
    return nil;
}

#pragma mark 设置角标
+ (void)set_badget_number_with:(UITabBarItem*)item  andCount:(NSString *)_XGpushMsgNum
{
    dispatch_async(dispatch_get_main_queue(), ^{
        item.badgeValue =_XGpushMsgNum;
    });
}


#pragma mark 计算文件出大小
+ (NSString *)fileSizeWithInterge:(NSInteger)size{
    // 1k = 1024, 1m = 1024k
    if (size < 1024) {// 小于1k
        return [NSString stringWithFormat:@"%ldB",(long)size];
    }else if (size < 1024 * 1024){// 小于1m
        CGFloat aFloat = size/1024;
        return [NSString stringWithFormat:@"%.0fK",aFloat];
    }else if (size < 1024 * 1024 * 1024){// 小于1G
        CGFloat aFloat = size/(1024 * 1024);
        return [NSString stringWithFormat:@"%.1fM",aFloat];
    }else{
        CGFloat aFloat = size/(1024*1024*1024);
        return [NSString stringWithFormat:@"%.1fG",aFloat];
    }
}

//遍历文件夹获得文件夹大小，返回多少M
+ (float ) folderSizeAtPath:(NSString*) folderPath{

    NSFileManager* manager = [NSFileManager defaultManager];

    if (![manager fileExistsAtPath:folderPath]) return 0;

    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];

    NSString* fileName;

    long long folderSize = 0;

    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [Tools fileSizeOnePath:fileAbsolutePath];
    }
        return folderSize;
}


+ (long long)fileSizeOnePath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}



+ (id)active_root_controller{
    UIApplication* app = [UIApplication sharedApplication];
    return app.keyWindow.rootViewController;
}


#pragma mark 判断字符串
//判断是否有中文
+(BOOL)IsChinese:(NSString *)str{
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}






@end
